<?php

declare(strict_types=1);

namespace App\Job\App;

use App\Exception\InternalException;
use App\Model\App\AppNotify;
use Hyperf\AsyncQueue\Job;
use App\Services\App\AppNotify as AppNotifyServices;
use App\Utils\Http\Request;
use Hyperf\Collection\Arr;
use function Hyperf\Support\make;

class Notify extends Job
{
    /**
     * 最大重试次数
     * @var int
     */
    protected int $maxAttempts = 7;

    /**
     * 参数
     * @var array
     */
    protected array $param;

    /**
     * 尽量不要将 Container，Config 等设置为成员变量。 同理 #[Inject] 也是如此
     * AutoCancelOrderJob constructor.
     * @param $param
     */
    public function __construct(array $param)
    {
        $this->param = $param;
    }

    /**
     * @throws \Throwable
     */
    public function handle()
    {
        [$appNotifyId] = $this->param;

        /** @var AppNotifyServices $appNotifyServices */
        $appNotifyServices = make(AppNotifyServices::class);
        /** @var AppNotify $appNotifyModel */
        $appNotifyModel = $appNotifyServices->findOrFail($appNotifyId);
        if ($appNotifyModel->status === 1) {
            return ;
        }
        try {
            /** @var Request $request */
            $request = make(Request::class);
            $request->setHeaders([
                'Accept' => 'application/json'
            ]);
            $request->setTimeout(5); // 设置超时时间5秒钟后未响应抛出异常
            $response = json_decode($request->{$appNotifyModel->request_type}($appNotifyModel->url, $appNotifyModel->request_info, true), true);
            $result = intval(!$response || Arr::get($response, 'code') != 200);
            if (!$response) {
                throw new InternalException(json_encode(['code' => 500, 'message' => 'response is null', 'data' => []]));
            }
            if ($result) {
                throw new InternalException(json_encode($response, JSON_UNESCAPED_UNICODE));
            }
            $appNotifyModel->increment('notify_num');
            $appNotifyModel->fill(['response_info'=>$response, 'status'=>1])->save();
        } catch (InternalException $internalException) {
            $appNotifyModel->increment('notify_num');
            $json = json_decode($internalException->getMessage(), true);
            if (!$json) {
                $json = ['code'=>500,'message'=>$internalException->getMessage(),'data'=>[]];
            }
            $appNotifyModel->fill(['response_info'=>$json, 'status'=>2])->save();
            throw $internalException;
        } catch (\Throwable $throwable) {
            $appNotifyModel->increment('notify_num');
            $appNotifyModel->fill(['response_info'=>['code'=>500,'message'=>$throwable->getMessage(),'data'=>[]], 'status'=>2])->save();
            throw $throwable;
        }
    }
}
